package com.hzit.sk.service.impl;

import com.hzit.sk.constant.RedisKeyConstant;
import com.hzit.sk.mapper.OrderInfoMapper;
import com.hzit.sk.model.OrderInfo;
import com.hzit.sk.mq.CreateOrderReq;
import com.hzit.sk.resp.Response;
import com.hzit.sk.service.ISkillService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 秒杀接口业务实现
 */
@Service
public class SkillServiceImpl implements ISkillService {


    @Autowired
    private ValueOperations valueOperations;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

//    @Autowired
//    private StringRedisTemplate stringRedisTemplate;

    Logger logger = LoggerFactory.getLogger(SkillServiceImpl.class);

    @Override
    public Response skill(String userId, String goodsId,String path) {

        Response response = new Response();

        String redisPath = (String)valueOperations.get(RedisKeyConstant.SKILL_PATH + userId+ goodsId);

        logger.info("redisPath = " + redisPath);

        if(StringUtils.isEmpty(redisPath)){
            logger.info("userId:{},goodsId:{}秒杀商品，请求地址为空");
            return Response.getFailData("地址非法");
        }

        if(!path.equals(redisPath)){
            logger.info("userId:{},goodsId:{}秒杀商品，请求地址非法");
            return Response.getFailData("地址非法");
        }


        //2.库存是否充足
        String redisKey = RedisKeyConstant.SKILL_GOODS_STOCK + goodsId;

        long stock =   valueOperations.decrement(redisKey,1l);

        logger.info("stock = " + stock);

        if (stock <0){
            //库存不足
            return Response.getFailData("库存不足");
        }

        //3.判断有过订单
        List<OrderInfo> orderInfoList = orderInfoMapper.queryByGoodsAndUserId(userId,goodsId);

        if(!CollectionUtils.isEmpty(orderInfoList)){
            return Response.getFailData("已经存在订单");
        }

        //4.生成订单，异步生成订单

        CreateOrderReq createOrderReq = new CreateOrderReq();
        createOrderReq.setGoodsCount("1");
        createOrderReq.setSkillPrice(""); //TODO
        createOrderReq.setGoodsId(goodsId);
        createOrderReq.setUserId(userId);
        amqpTemplate.convertAndSend("skill.exchange.topic","send.order",createOrderReq);


        return Response.getSuccessData("请求成功");
    }
}
